import { createRouter, createWebHistory } from 'vue-router'
import { jwtDecode } from 'jwt-decode'
import type { JwtPayload } from '@/types/public'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', name: 'login', component: () => import('@/views/loginPage.vue') }, //登录页
    {
      path: '/',
      name: 'layoutContainer',
      component: () => import('@/views/layoutContainer.vue'),
      redirect: (to) => {
        try {
          const useStore = useUserStore()
          const decode = jwtDecode<JwtPayload>(useStore.token)
          const role = decode['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
          // 根据角色重定向
          if (role === 'Student') return '/student/course'
          if (role === 'Teacher') return '/teacher/qrcode'
          if (role === 'Admin') return '/admin/class'
        } catch (err) {
          return '/login'
        }
      },
      children: [
        // 教师路由
        {
          path: '/teacher/qrcode',
          component: () => import('@/views/teacher/QrcodePage.vue'),
        },
        {
          path: '/teacher/course',
          component: () => import('@/views/teacher/CoursePage.vue'),
        },
        {
          path: '/teacher/attendance',
          component: () => import('@/views/teacher/AttendancePage.vue'),
        },
        // 学生路由
        {
          path: '/student/course',
          component: () => import('@/views/student/CoursePage.vue'),
        },
        // 管理员路由
        {
          path: '/admin/class',
          component: () => import('@/views/admin/ClassManagePage.vue'),
        },
      ],
    }, //布局容器
  ],
})

// 登录访问拦截 => 默认是直接放行的
// 根据返回值决定，是放行还是拦截
// 返回值：
// 1. undefined / true  直接放行
// 2. false 拦回from的地址页面
// 3. 具体路径 或 路径对象  拦截到对应的地址
//    '/login'   { name: 'login' }
router.beforeEach((to) => {
  // 如果没有token, 且访问的是非登录页，拦截到登录，其他情况正常放行
  const useStore = useUserStore()
  if (!useStore.token && to.path !== '/login') return '/login'
})

export default router
